﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Engine;
using Gencode;
using Library;
using MyControls;
namespace GameTool
{
    public partial class CocVang_Form1 : Form
    {
        public MainForm mainForm;
        private int iEasy;
        private int iNomal;
        private int iHard;
        private string sLop="",sVong="";

        private string GetXMLPath()
        {
            return Common.config.pathXml + "\\" + this.cmbLop.Text + "\\Game4";
        }

        private string GetImagePath()
        {
            return Common.config.pathImage + "\\" + cmbLop.Text + "\\Game4";
        }

        public CocVang_Form1()
        {
            InitializeComponent();
            InitData();
        }

        private void CocVang_Form1_Load(object sender, EventArgs e)
        {
            Top = 0;
            if (cmbLop.Items.Count>0)
            {
                cmbLop.SelectedIndex = 0;
            }
            Height = SystemInformation.VirtualScreen.Size.Height - (Screen.PrimaryScreen.Bounds.Bottom - Screen.PrimaryScreen.WorkingArea.Bottom);
        }

        private void cmdAdd_Click(object sender, EventArgs e)
        {
            CocVang cocVang = new CocVang();
            TabPage tab = (TabPage)tabControl1.Controls[tabControl1.SelectedIndex];
            int iItem = CountQuestion(tab);
            cocVang.iIndex = iItem;
            if(iItem==0)
            {
                cocVang.Location = new Point(6, 0);
            }
            else
            {
                cocVang.Location = new Point(6, tab.Controls[iItem - 1].Location.Y + tab.Controls[iItem - 1].Height);    
            }
            cocVang.EventDelete += Delete_Click;
            tab.Controls.Add(cocVang);
            UpdateCount();
        }
        private int CountQuestion(TabPage tab)
        {
            int n = 0;
            foreach (CocVang control in tab.Controls)
            {
                n++;
            }
            return n;
        }

        private void InitData()
        {
            try
            {
                foreach (ClassInfo c in Common.ClassList)
                {
                    if (User.CheckPermission(c.Name))
                    {
                        cmbLop.Items.AddRange(new object[] { "lop" + c.Name });
                    }
                }
                if (cmbLop.Items.Count > 0)
                {
                    cmbLop.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            CocVang oCocVang = (CocVang)((GroupBox)(((Button)sender).Parent).Parent).Parent;
            if(MessageBox.Show("Bạn có muốn xóa câu hỏi " + (oCocVang.iIndex+1).ToString() + " không?","xác nhận",MessageBoxButtons.YesNo,MessageBoxIcon.Question)!=DialogResult.Yes) return;
            TabPage tab = (TabPage) oCocVang.Parent;
            foreach (CocVang cocVang in tab.Controls)
            {
                if (cocVang.Top > oCocVang.Top && cocVang!=oCocVang)
                {
                    cocVang.iIndex--;
                    cocVang.Location = new Point(cocVang.Location.X,cocVang.Location.Y-cocVang.Height);
                }
            }
            oCocVang.Dispose();
            UpdateCount();
        }

        private void UpdateCount()
        {
            TabPage tab = (TabPage)tabControl1.Controls[tabControl1.SelectedIndex];
            int iItem = CountQuestion(tab);
            if (tabControl1.SelectedIndex == 0)
            {
                iEasy = iItem;
                tab.Text = string.Format("Câu dễ ({0})", iEasy);
            }
            if (tabControl1.SelectedIndex == 1)
            {
                iNomal = iItem;
                tab.Text = string.Format("Trung bình ({0})", iNomal);
            }
            if (tabControl1.SelectedIndex == 2)
            {
                iHard = iItem;
                tab.Text = string.Format("Câu dễ ({0})", iHard);
            }
            txtCounter.Text = (iEasy + iNomal + iHard).ToString();
        }

        private void Upload_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult _dialogResult;
                string _mess;
                #region Validate?
                _mess = ValidateInput();
                if (_mess.Length > 0)
                {
                    _mess += "\nVui lòng kiểm tra lại!";
                    MessageBox.Show(_mess, "Thong bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                #endregion
                #region Exists?

                bool _exists = ftp_main.CheckExists(GetXMLPath() + "\\" + cmbVong.Text, "1.xml");
                if (_exists)
                {
                    _dialogResult = MessageBox.Show("Đề bài của lớp này, vòng này đã có. Bạn có muốn ghi đè hay không?",
                                                   "Xac nhan thao tac", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (_dialogResult == DialogResult.No)
                    {
                        return;
                    }
                }
                #endregion

                //#region Validate?
                //_mess = string.Empty;
                //if (!OK(out _mess))
                //{
                //    string[] _xy = _mess.Split(';');
                //    MessageBox.Show("Phần tử [" + (int.Parse(_xy[1]) + 1).ToString() + "] " + Common.Level[_xy[0]] + " không hợp lệ.\nVui lòng kiểm tra lại",
                //                                   "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}
                //#endregion

                #region Warning
                _mess = Warning();
                if (_mess.Length > 0)
                {
                    _mess += "\nBạn có muốn tải lên server?";
                    _dialogResult = MessageBox.Show(_mess, "Xac nhan thao tac", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (_dialogResult == DialogResult.No)
                    {
                        return;
                    }
                }
                #endregion
                string result = UploadXML();
                result+=UploadQuestionXML();
                if (result.Length > 0)
                {
                    MessageBox.Show(result);
                }
                else
                {
                    Common.LogAction(Library.Action.Update);
                    MessageBox.Show("Tải đề lên server thành công!", "Thong bao", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }

                _mess = Warning();
                if (_mess.Length > 0)
                    MessageBox.Show(_mess, "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        /// <summary>
        /// Đẩy dữ liệu lên server
        /// </summary>
        /// <returns></returns>
        private string UploadQuestionXML()
        {
            string result = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);
                XmlNode examinateNode = doc.CreateElement("Examinates");
                doc.AppendChild(examinateNode);

                XmlNode questionsNode = doc.CreateElement("questions");

                //get question Easy
                foreach (CocVang cocVang in Tab_Easy.Controls)
                {
                    XmlNode questionNode = doc.CreateElement("question");
                    XmlAttribute attr = doc.CreateAttribute("type");
                    attr.Value = "0";
                    questionNode.Attributes.Append(attr);

                    attr = doc.CreateAttribute("typeTest");
                    attr.Value = cmbVong.Text.Substring(5, cmbVong.Text.Length - 5);
                    questionNode.Attributes.Append(attr);

                    XmlNode levelNode = doc.CreateElement("level");
                    levelNode.AppendChild(doc.CreateTextNode("0"));
                    questionNode.AppendChild(levelNode);

                    XmlNode codeNode = doc.CreateElement("code");
                    codeNode.AppendChild(doc.CreateTextNode(cocVang.iIndex.ToString()));
                    questionNode.AppendChild(codeNode);
                    
                    cocVang.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));//create image
                    XmlNode subjectNode = doc.CreateElement("subject");
                    subjectNode.AppendChild(doc.CreateTextNode(cocVang.ChildFileName));
                    questionNode.AppendChild(subjectNode);
                    if (cocVang.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.ChildFileName, cocVang.FullPath);
                    }

                    //answers
                    XmlNode answersNode = doc.CreateElement("answers");
                    //answer 1
                    cocVang.cocVang_DapAn1.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode1 = doc.CreateElement("answer");
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn1.ChildFileName));
                    if (cocVang.cocVang_DapAn1.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn1.ChildFileName, cocVang.cocVang_DapAn1.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue==1)?"1":"0";
                    answerNode1.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode1);
                    //answer 2
                    cocVang.cocVang_DapAn2.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode2 = doc.CreateElement("answer");
                    answerNode2.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    if (cocVang.cocVang_DapAn2.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn2.ChildFileName, cocVang.cocVang_DapAn2.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 2) ? "1" : "0";
                    answerNode2.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode2);
                    //answer 3
                    cocVang.cocVang_DapAn3.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode3 = doc.CreateElement("answer");
                    answerNode3.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    if (cocVang.cocVang_DapAn3.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn3.ChildFileName, cocVang.cocVang_DapAn3.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 3) ? "1" : "0";
                    answerNode3.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode3);
                    //answer 4
                    cocVang.cocVang_DapAn4.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode4 = doc.CreateElement("answer");
                    answerNode4.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn4.ChildFileName));
                    if (cocVang.cocVang_DapAn4.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn4.ChildFileName, cocVang.cocVang_DapAn4.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 4) ? "1" : "0";
                    answerNode4.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode4);
                    //
                    questionNode.AppendChild(answersNode);
                    questionsNode.AppendChild(questionNode);
                }

                //get question Nomal
                foreach (CocVang cocVang in Tab_Nomal.Controls)
                {
                    XmlNode questionNode = doc.CreateElement("question");
                    XmlAttribute attr = doc.CreateAttribute("type");
                    attr.Value = "0";
                    questionNode.Attributes.Append(attr);

                    attr = doc.CreateAttribute("typeTest");
                    attr.Value = cmbVong.Text.Substring(5, cmbVong.Text.Length - 5);
                    questionNode.Attributes.Append(attr);

                    XmlNode levelNode = doc.CreateElement("level");
                    levelNode.AppendChild(doc.CreateTextNode("1"));
                    questionNode.AppendChild(levelNode);

                    XmlNode codeNode = doc.CreateElement("code");
                    codeNode.AppendChild(doc.CreateTextNode(cocVang.iIndex.ToString()));
                    questionNode.AppendChild(codeNode);

                    cocVang.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));//create image
                    XmlNode subjectNode = doc.CreateElement("subject");
                    subjectNode.AppendChild(doc.CreateTextNode(cocVang.ChildFileName));
                    questionNode.AppendChild(subjectNode);
                    if (cocVang.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.ChildFileName, cocVang.FullPath);
                    }

                    //answers
                    XmlNode answersNode = doc.CreateElement("answers");
                    //answer 1
                    cocVang.cocVang_DapAn1.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode1 = doc.CreateElement("answer");
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn1.ChildFileName));
                    if (cocVang.cocVang_DapAn1.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn1.ChildFileName, cocVang.cocVang_DapAn1.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 1) ? "1" : "0";
                    answerNode1.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode1);
                    //answer 2
                    cocVang.cocVang_DapAn2.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode2 = doc.CreateElement("answer");
                    answerNode2.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    if (cocVang.cocVang_DapAn2.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn2.ChildFileName, cocVang.cocVang_DapAn2.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 2) ? "1" : "0";
                    answerNode2.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode2);
                    //answer 3
                    cocVang.cocVang_DapAn3.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode3 = doc.CreateElement("answer");
                    answerNode3.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    if (cocVang.cocVang_DapAn3.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn3.ChildFileName, cocVang.cocVang_DapAn3.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 3) ? "1" : "0";
                    answerNode3.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode3);
                    //answer 4
                    cocVang.cocVang_DapAn4.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode4 = doc.CreateElement("answer");
                    answerNode4.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn4.ChildFileName));
                    if (cocVang.cocVang_DapAn4.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn4.ChildFileName, cocVang.cocVang_DapAn4.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 4) ? "1" : "0";
                    answerNode4.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode4);
                    //
                    questionNode.AppendChild(answersNode);
                    questionsNode.AppendChild(questionNode);
                }

                //get question hard
                foreach (CocVang cocVang in Tab_hard.Controls)
                {
                    XmlNode questionNode = doc.CreateElement("question");
                    XmlAttribute attr = doc.CreateAttribute("type");
                    attr.Value = "0";
                    questionNode.Attributes.Append(attr);

                    attr = doc.CreateAttribute("typeTest");
                    attr.Value = cmbVong.Text.Substring(5, cmbVong.Text.Length - 5);
                    questionNode.Attributes.Append(attr);

                    XmlNode levelNode = doc.CreateElement("level");
                    levelNode.AppendChild(doc.CreateTextNode("2"));
                    questionNode.AppendChild(levelNode);

                    XmlNode codeNode = doc.CreateElement("code");
                    codeNode.AppendChild(doc.CreateTextNode(cocVang.iIndex.ToString()));
                    questionNode.AppendChild(codeNode);

                    cocVang.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));//create image
                    XmlNode subjectNode = doc.CreateElement("subject");
                    subjectNode.AppendChild(doc.CreateTextNode(cocVang.ChildFileName));
                    questionNode.AppendChild(subjectNode);
                    if (cocVang.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.ChildFileName, cocVang.FullPath);
                    }

                    //answers
                    XmlNode answersNode = doc.CreateElement("answers");
                    //answer 1
                    cocVang.cocVang_DapAn1.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode1 = doc.CreateElement("answer");
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn1.ChildFileName));
                    if (cocVang.cocVang_DapAn1.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn1.ChildFileName, cocVang.cocVang_DapAn1.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 1) ? "1" : "0";
                    answerNode1.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode1);
                    //answer 2
                    cocVang.cocVang_DapAn2.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode2 = doc.CreateElement("answer");
                    answerNode2.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn2.ChildFileName));
                    if (cocVang.cocVang_DapAn2.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn2.ChildFileName, cocVang.cocVang_DapAn2.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 2) ? "1" : "0";
                    answerNode2.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode2);
                    //answer 3
                    cocVang.cocVang_DapAn3.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode3 = doc.CreateElement("answer");
                    answerNode3.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    answerNode1.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn3.ChildFileName));
                    if (cocVang.cocVang_DapAn3.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn3.ChildFileName, cocVang.cocVang_DapAn3.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 3) ? "1" : "0";
                    answerNode3.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode3);
                    //answer 4
                    cocVang.cocVang_DapAn4.MyCapture(int.Parse(cmbLop.Text.Substring(3, cmbLop.Text.Length - 3)));
                    XmlNode answerNode4 = doc.CreateElement("answer");
                    answerNode4.AppendChild(doc.CreateTextNode(cocVang.cocVang_DapAn4.ChildFileName));
                    if (cocVang.cocVang_DapAn4.Modify)
                    {
                        UploadFile.UpFtpFile(GetImagePath(), cmbVong.Text, cocVang.cocVang_DapAn4.ChildFileName, cocVang.cocVang_DapAn4.FullPath);
                    }
                    attr = doc.CreateAttribute("value");
                    attr.Value = (cocVang.SelectedTrue == 4) ? "1" : "0";
                    answerNode4.Attributes.Append(attr);
                    answersNode.AppendChild(answerNode4);
                    //
                    questionNode.AppendChild(answersNode);
                    questionsNode.AppendChild(questionNode);
                    examinateNode.AppendChild(questionsNode);
                }

                string xmlFile = "question.xml";
                doc.Save(xmlFile);
                UploadFile.UpFtpFile(GetXMLPath(), cmbVong.Text, xmlFile, xmlFile);
                System.IO.File.Delete(xmlFile);
                //INSERT();//insert database
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
            return result;
        }

        private string UploadXML()
        {
            string result = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);
                XmlNode examinateNode = doc.CreateElement("Examinates");
                doc.AppendChild(examinateNode);

                XmlNode pointNode = doc.CreateElement("point");
                pointNode.AppendChild(doc.CreateTextNode(nUDDiem.Text)); // point= nUDDiem
                examinateNode.AppendChild(pointNode);

                XmlNode timeNode = doc.CreateElement("time");
                timeNode.AppendChild(doc.CreateTextNode(nUDThoiGian.Text));//time=nUDThoiGian
                examinateNode.AppendChild(timeNode);

                XmlNode codeNode = doc.CreateElement("code");
                codeNode.AppendChild(doc.CreateTextNode(cmbVong.Text.Substring(5, cmbVong.Text.Length - 5)));//code=level
                examinateNode.AppendChild(codeNode);

                XmlNode numErrorNode = doc.CreateElement("numError");
                numErrorNode.AppendChild(doc.CreateTextNode(nUDSoLoi.Text)); // numError
                examinateNode.AppendChild(numErrorNode);

                XmlNode numLevel1Node = doc.CreateElement("numLevel1");
                numLevel1Node.AppendChild(doc.CreateTextNode(nUDDe.Text)); // numLevel1
                examinateNode.AppendChild(numLevel1Node);

                XmlNode numLevel2Node = doc.CreateElement("numLevel2");
                numLevel2Node.AppendChild(doc.CreateTextNode(nUDBinhThuong.Text)); // numLevel2
                examinateNode.AppendChild(numLevel2Node);

                XmlNode numLevel3Node = doc.CreateElement("numLevel3");
                numLevel3Node.AppendChild(doc.CreateTextNode(nUDKho.Text)); // numLevel3
                examinateNode.AppendChild(numLevel3Node);

                string xmlFile = "1.xml";
                doc.Save(xmlFile);
                UploadFile.UpFtpFile(GetXMLPath(), cmbVong.Text, xmlFile, xmlFile);
                System.IO.File.Delete(xmlFile);
                //INSERT();//insert database
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
            return result;
        }

        private string getFileName(string spath)
        {
            int i = spath.LastIndexOf("\\");
            if (i < spath.Length)
            {
                return spath.Substring(i + 1, spath.Length-i-1);    
            }
            return "";
        }

        private void cmdTaoDeMoi_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult _dialogResult =
                    MessageBox.Show("Dữ liệu sẽ bị mất nếu bạn chưa tải lên server. Bạn có chắc chắn muốn tạo mới?\n\n\n(Nhấn Yes chương trình sẽ xóa bỏ mọi dữ liệu hiện có, nếu bạn chưa tải lên server\nNhấn No để giữ nguyên trạng thái)",
                        "Xac nhan thao tac", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (_dialogResult == DialogResult.Yes)
                    Reset();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void Reset()
        {
            if (cmbLop.Items.Count > 0)
                cmbLop.SelectedIndex = 0;
            cmbVong.SelectedIndex = 0;
            nUDThoiGian.Value = nUDThoiGian.Minimum;
            nUDDe.Value = nUDDe.Minimum;
            nUDBinhThuong.Value = nUDBinhThuong.Minimum;
            nUDKho.Value = nUDKho.Minimum;
            nUDDiem.Value = nUDDiem.Minimum;
            //
            CearQuestion();
        }

        private void CearQuestion()
        {
            foreach (CocVang cocVang in Tab_Easy.Controls)
            {
                cocVang.Dispose();
            }
            foreach (CocVang cocVang in Tab_Nomal.Controls)
            {
                cocVang.Dispose();
            }
            foreach (CocVang cocVang in Tab_hard.Controls)
            {
                cocVang.Dispose();
            }
        }

        private void Review_Click(object sender, EventArgs e)
        {
            DialogResult _dialogResult =
                    MessageBox.Show(
                        "Dữ liệu sẽ bị mất nếu bạn chưa tải lên server. Bạn có chắc chắn muốn xem đề?\n\n\n(Nhấn Yes chương trình sẽ xóa bỏ mọi dữ liệu hiện có, nếu bạn chưa tải lên server\nNhấn No để giữ nguyên trạng thái)",
                        "Xac nhan thao tac", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (_dialogResult == DialogResult.No)
                return;

            try
            {
                CocVang_Form2 form2 = new CocVang_Form2(GetXMLPath());
                form2.sender = new CocVang_Form2.sendPram(send);
                form2.ShowDialog();
                String url = GetXMLPath() + @"\" + sVong;
                if (sLop.Length > 0 && sVong.Length > 0)
                {
                    pnlCmd.Visible = tabControl1.Visible = true;
                    //clear question
                    CearQuestion();
                    LoadXML(url, "1.xml");
                    LoadQuestionXML(url, "question.xml");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void send(string sLop, string sVong)
        {
            this.sLop = sLop;
            this.sVong = sVong;
        }

        private void LoadXML(string url, string filename)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();

                ftp_main.download(url, filename);
                xDoc.Load(filename);

                cmbLop.Text = sLop;
                cmbVong.Text = sVong;

                // Parser File Xml.
                XmlNodeList pointNode = xDoc.GetElementsByTagName("point");
                string point = pointNode[0].InnerText;
                this.nUDDiem.Value = Int32.Parse(point);

                XmlNodeList time = xDoc.GetElementsByTagName("time");
                string timeString = time[0].InnerText;
                this.nUDThoiGian.Value = Int32.Parse(timeString);

                XmlNodeList code = xDoc.GetElementsByTagName("code");
                string codeString ="level" + code[0].InnerText;
                cmbVong.Text = codeString;

                XmlNodeList numError = xDoc.GetElementsByTagName("numError");
                string numErrorString = numError[0].InnerText;
                nUDSoLoi.Value = Int32.Parse(numErrorString);

                XmlNodeList xnumLevel1 = xDoc.GetElementsByTagName("numLevel1");
                string numLevel1String = xnumLevel1[0].InnerText;
                nUDDe.Value = Int32.Parse(numLevel1String);

                XmlNodeList xnumLevel2 = xDoc.GetElementsByTagName("numLevel2");
                string numLevel2String= xnumLevel2[0].InnerText;
                nUDBinhThuong.Value = Int32.Parse(numLevel2String);

                XmlNodeList xnumLevel3 = xDoc.GetElementsByTagName("numLevel3");
                string numLevel3String = xnumLevel3[0].InnerText;
                nUDKho.Value = Convert.ToByte(numLevel3String);
                //ShowCom(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void LoadQuestionXML(string url, string filename)
        {
            
        }

        /// <summary>
        /// Kiểm tra tính hợp lệ của dữ liệu đầu vào trước khi lưu
        /// </summary>
        /// <returns>Thông điệp trả về: thông điệp trắng là hợp lệ</returns>
        private string ValidateInput()
        {
            string _mess = string.Empty;
            try
            {
                //if (!chkViolympic.Checked && !chkViSchool.Checked && !chkViother.Checked)
                //{
                //    _mess = "Bạn chưa chọn nhập liệu cho chương trình nào.";
                //    chkViolympic.Focus();
                //    return _mess;
                //}
                if (cmbLop.SelectedIndex < 0)
                {
                    _mess = "Bạn chưa chọn lớp.";
                    cmbLop.DroppedDown = true;
                    cmbLop.Focus();
                    return _mess;
                }
                if (cmbVong.SelectedIndex < 0)
                {
                    _mess = "Bạn chưa chọn Vòng.";
                    cmbVong.DroppedDown = true;
                    cmbVong.Focus();
                    return _mess;
                }

                int _totalQuestion = (int)(nUDDe.Value + nUDBinhThuong.Value + nUDKho.Value);
                if (_totalQuestion == 0)
                {
                    _mess = "S. câu dễ + S. câu tb + S. câu khó > 0.";
                    nUDDe.Focus();
                    return _mess;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
            return _mess;
        }

        private string Warning()
        {
            string _mess = string.Empty;
            try
            {
                if (iEasy < nUDDe.Value)
                {
                    if (_mess.Length > 0)
                        _mess += "\n";
                    _mess += "- S. câu dễ chưa đủ";
                }

                if (iNomal < nUDBinhThuong.Value)
                {
                    if (_mess.Length > 0)
                        _mess += "\n";
                    _mess += "- S. câu tb chưa đủ";
                }

                if (iHard < nUDKho.Value)
                {
                    if (_mess.Length > 0)
                        _mess += "\n";
                    _mess += "- S. câu khó chưa đủ";
                }

                if (_mess.Length > 0)
                    _mess += "\nđể game chạy!";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
            return _mess;
        }

        private void cmbLop_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                cmbVong.Items.Clear();
                foreach (RoundInfo roundInfo in Common.RoundList[cmbLop.SelectedIndex])
                {
                    this.cmbVong.Items.AddRange(new object[] { "level" + roundInfo.RoundNumber });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }
    }
}
